package com.py.credit.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ResourceDataCleanFieldsEnum;
import com.py.credit.service.DataCleanService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/dataClean")
public class DataCleanController {

	private static final int ZERO = 0;

	private static final String ZERO_STR = "0";

	private final static String FRONT_TABLE_ID = "dataClean";

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private DataCleanService dataCleanService;

	/**
	 * 获取初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(ResourceDataCleanFieldsEnum.getOptionalColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;

	}

	/**
	 * @api {get} /dataClean/getTableList.json 获取表规则列表
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 表规则管理
	 * 
	 * @apiParam {String} condition 查询条件(可选)
	 * @apiParam {int} limit 每页展示条数 (必需)
	 * @apiParam {int} page 当前页数 (必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":2,"data":[{"rule_package":"1222","rule_desc":"122222","rule_name":"1","rule_method":"123","id":22,"time":"2018-04-23","managerName":"超级管理员"},{"rule_package":"555","rule_desc":"5555","rule_name":"555","rule_method":"555","id":35,"time":"2018-04-26","managerName":"超级管理员"}]}
	 * 
	 */
	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<Map<String, Object>>> getTableList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementCountController#getAchievementCount", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);

		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourceDataCleanFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		try {
			List<Map<String, Object>> tableList = dataCleanService.getByConditionForPage(showColumns, null, condition,
					page);
			result = new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常！");
		}
		return result;

	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(ResourceDataCleanFieldsEnum.getAdvancedConditionColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;

	}

	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}

			String column = StringUtils.join(columns, ",");
			// column = column;
			MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, StringUtils.split(column, ","));
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return result;
	}

	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/getDetail.json")
	public RestServiceResult<Object> getDetail(@RequestParam(value = "channelId", required = true) String channelId) {
		RestServiceResult<Object> r = new RestServiceResult<Object>();
		try {
			r = new RestServiceResult<Object>(dataCleanService.getDetail(channelId));
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}

	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/getRecentMonthTime.json")
	public RestServiceResult<Object> getRecentMonthTime(@RequestParam(value = "time", required = true) String time) {
		RestServiceResult<Object> r = new RestServiceResult<Object>();
		try {
			r = new RestServiceResult<Object>(dataCleanService.getRecentMonthTime(time));
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("获取时间范围异常！");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
}
